#include "process.h"

static int idata = 111;

void processDemo(){
    int istack = 222;
    pid_t childPid;

    switch (childPid = fork())
    {
    case -1:
        exit(-1);
        break;

    case 0:
        idata *= 3;
        istack *= 3;
        break;
    
    default:
        sleep(3); // 使得主进程休眠，子进程先执行
        break;
    }

    printf("PID=%ld %s  idata=%d,istack=%d\n",(long)getpid(),(childPid == 0) ?"(child)" :"(parent)",idata,istack);
    return;
}


void fileShareDemo(){
    int fd,flags;
    char templatep[] = "/tmp/test";

    setbuf(stdout,NULL);
    fd = mkstemp(templatep);
    if (fd == - 1){
        exit(-1);
    }

    printf("File offset before fork():%lld\n",(long long)lseek(fd,0,SEEK_CUR));
    flags = fcntl(fd,F_GETFL);
    if (flags == -1){
        exit(-1);
    }

    printf("O_APPEND flag before fork() is: %s\n",(flags & O_APPEND) ? "ON" :"OFF");

    switch (fork())
    {
    case -1:
        exit(-1);
        break;

    case 0:
        if(lseek(fd,1000,SEEK_SET) == - 1){
            exit(-1);
        }

        flags = fcntl(fd,F_GETFL);
        if (flags == -1){
            exit(-1);
        }

        flags |= O_APPEND;
        if (fcntl(fd,F_SETFL,flags) == -1){
            exit(-1);
        }

        return;

        break;
    default:
        if (wait(NULL) == -1){
            exit(-1);
        }

        printf("child has exited\n");
        printf("file offset in parent:%lld\n",(long long )lseek(fd,0,SEEK_CUR));

        flags = fcntl(fd,F_GETFL);
        if (flags == -1){
            exit(-1);
        }

        printf("O_APPEND flag before fork() is: %s\n",(flags & O_APPEND) ? "ON" :"OFF");

        return;

        break;
    }




}